package com.bawei.shoppingcar;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.bawei.shoppingcar.adapter.GoodsAdapter;
import com.bawei.shoppingcar.entity.GoodsEntity;
import com.bawei.shoppingcar.utils.HttpUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private GridView gv;
    private List<GoodsEntity.DataBean> list = new ArrayList<>();
    private GoodsAdapter adpater;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gv = findViewById(R.id.gv);
        adpater = new GoodsAdapter(list,this);
        gv.setAdapter(adpater);
        new GoodsTask().execute("http://43.143.146.165:8083/goods/getAllGoods?goods_category=0");
        //点击跳转到详情页面
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent =   new Intent(MainActivity.this, GoodsDetailActivity.class);
                Bundle bundle = new Bundle();//包
                bundle.putSerializable("goods",list.get(i));
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
    }
    class GoodsTask extends AsyncTask<String,Integer,String> {
        @Override
        protected String doInBackground(String... strings) {
            return HttpUtils.doGet(strings[0]);
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
            GoodsEntity goodsEntity = new Gson().fromJson(s, GoodsEntity.class);
            List<GoodsEntity.DataBean> data = goodsEntity.getData();
            list.addAll(data);
            adpater.notifyDataSetChanged();
        }
    }
}